//
//  MyGiftViewController.m
//  Molian
//
//  Created by xiaocankeji on 15/8/12.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "MyGiftViewController.h"
#import "MyGiftTableViewCell.h"
#import "MLUserDataViewController.h"
#import "SRRefreshView.h" //下拉刷新

#import "UIScrollView+DXRefresh.h"//上拉
#define USER_NUM_PER_TIME 20
@interface MyGiftViewController ()<UITableViewDelegate,SRRefreshDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)NSMutableArray *giftArr;
@property (nonatomic, strong) Utils *uview;
//下拉刷新
@property (strong, nonatomic) SRRefreshView *slimeView;
// 当前分页
@property NSUInteger currentPage;

@end

@implementation MyGiftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"礼物";
    // 从导航条以下开始计算
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavigationBarHeight, DeviceWidth, DeviceHeight-kNavigationBarHeight) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.scrollsToTop = YES;
    self.tableView.separatorColor = RGBA(229, 229, 229, 1);//分隔条颜色
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0,10, 0);//偏移量
    self.tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, CGFLOAT_MIN)];
    //self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    self.tableView.tableFooterView = [[UIView alloc] init];//不显示空的cell
    //    [self.tableView setSeparatorInset:UIEdgeInsetsMake(0, -20, 0, 0)];
    [self.view addSubview:self.tableView];
    //上拉加载
    [self.tableView addFooterWithTarget:self action:@selector(requestData)];
    _slimeView = [[SRRefreshView alloc] init];
    _slimeView.delegate = self;
    _slimeView.upInset = 0;
    _slimeView.slimeMissWhenGoingBack = YES;
    _slimeView.slime.bodyColor = APPCOLOR(1);
    _slimeView.slime.skinColor = [UIColor whiteColor];
    _slimeView.slime.lineWith = 1;
    _slimeView.slime.shadowBlur = 0;
    _slimeView.slime.shadowColor = [UIColor redColor];
    [self.tableView addSubview:self.slimeView];
    // Do any additional setup after loading the view.
    [self pageRequestData];
    self.uview = [[Utils alloc]init];
    [_uview viewControllerPrompt:self.view.bounds Text:@"还没有收到礼物\n谁会第一个给你送礼物呢" Image:[UIImage imageNamed:@"xinlianren_nul"]];
    [self. view addSubview:_uview.viewPrompt];
    
    // Do any additional setup after loading the view.
}
- (void)pageRequestData
{
    // 当前分页归零
    self.currentPage = 0;
    [self requestData];
    
    
}
- (NSMutableArray *)giftArr
{
    if (_giftArr == nil) {
        _giftArr = [NSMutableArray array];
    }
    return _giftArr;
}
- (void)requestData
{
    AVQuery *query = [MLGiftRecord query];
    [query whereKey:@"receiver" equalTo:[MLUser currentUser]];
    [query includeKey:@"user"];
    [query includeKey:@"gift"];
    query.limit = USER_NUM_PER_TIME;
    query.skip = self.currentPage*USER_NUM_PER_TIME;
    [query orderByDescending:@"createdAt"];
    [HUD setOnViewWithTitle:@"加载中" animated:YES];
    
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       
        //停止加载
        [_slimeView endRefresh];
         [HUD hideFromViewAnimated:YES];
         [self.tableView footerEndRefreshing];
        if (error) {
            [HUD Prompt:@"网络错误"];
        }else{
            if (self.currentPage == 0) {
                [self.giftArr removeAllObjects];
            }
           
            [self.giftArr addObjectsFromArray:objects];
             self.currentPage++;
            [self.tableView reloadData];
            if ([self.giftArr count] == 0) {
                _uview.viewPrompt.hidden = NO;
            }else{
                _uview.viewPrompt.hidden = YES;
            }
        }
    }];
}
- (void)slimeRefreshStartRefresh:(SRRefreshView *)refreshView
{
    [self pageRequestData];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_slimeView) {
        [_slimeView scrollViewDidScroll];
    }
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [_slimeView scrollViewDidEndDraging];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *cellIndentifier = @"myGiftCell";
    MyGiftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[MyGiftTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    if ([self.giftArr count]) {
        MLGiftRecord *giftRecord = self.giftArr[indexPath.row];
        MLUser *user = (MLUser *)giftRecord.user;
        if (!user.subAvatar || [user.subAvatar isEqualToString:@""]) {
            [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:user.avatar.url] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
            
        }else{
            [cell.userAvatarImg sd_setImageWithURL:[NSURL URLWithString:user.subAvatar] placeholderImage:[UIImage imageNamed:@"common_avatar_loading_background"]];
        }
        cell.userNameLabel.text = user.nickname;
            MLGift *gift = (MLGift *)giftRecord.gift;
        [cell.giftAvatarImg sd_setImageWithURL:[NSURL URLWithString:gift.img.url] placeholderImage:[UIImage imageNamed:@"chat_gift_icon"]];
        cell.giftNameLabel.text = [NSString stringWithFormat:@"%@x1",gift.name];
        cell.giftSignatureLabel.text = gift.info;
        cell.timeLabel.text = [TimeUtils getPastTimeWithDate:giftRecord.createdAt];;
    }
    
    return cell;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}
//cell数目
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.giftArr count];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MLGiftRecord *giftRecord = self.giftArr[indexPath.row];
    MLUser *user = (MLUser *)giftRecord.user;
    MLUserDataViewController *userInfoVC = [[MLUserDataViewController alloc]init];
    userInfoVC.userData =user;
    [Utils pushTabbarHidden:userInfoVC Selfvc:self];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
